import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'index',
      component: () => import('@/views/layout.vue'),
      children: [
        {
          path: '/admin',
          name: 'admin',
          component: () => import('@/views/admin/index.vue')
        },
        {
          path: '/docu',
          name: 'docu',
          component: () => import('@/views/docu/index.vue')
        },
        {
          path: '/about',
          name: 'about',
          component: () => import('@/views/about/index.vue')
        },
        {
          path: '/update',
          name: 'update',
          component: () => import('@/views/update/index.vue')
        },
        {
          path: '/reset',
          name: 'reset',
          component: () => import('@/views/reset/index.vue')
        },
        {
          path: '/vue',
          name: 'vue',
          component: () => import('@/iframe/vue.vue')
        },
        {
          path: '/element',
          name: 'element',
          component: () => import('@/iframe/elementPlus.vue')
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/register/index.vue')
    },
    {
      redirect: '/admin'
    }
  ]
})

const authRoutes = ['/admin', '/docu', '/about', '/update', '/reset']

router.beforeEach((to) => {
  const userStore = useUserStore()
  if (authRoutes.includes(to.path) && !userStore.userInfo?.isLogin) return { name: 'login' }
  else return true
})

export default router
